package com.liusaidh.exception;

import com.liusaidh.result.Result;
import com.liusaidh.result.Status;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;


/**
 * @author liusaidh
 * @date 2024/5/16 20:05
 * @description 全局异常
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ResponseBody
    @ExceptionHandler(value = ConstraintViolationException.class)
    public Result constraintViolationExceptionHandler(ConstraintViolationException ex) {
        log.debug("[constraintViolationExceptionHandler]", ex);
        StringBuilder detailMessage = new StringBuilder();
        for (ConstraintViolation<?> constraintViolation : ex.getConstraintViolations()) {
            // 使用 ; 分隔多个错误
            if (detailMessage.length() > 0) {
                detailMessage.append(";");
            }
            // 拼接内容到其中
            detailMessage.append(constraintViolation.getMessage());
        }
        // 包装 Result 结果
        return Result.fail(Status.INVALID_REQUEST_PARAM_ERROR,
                Status.INVALID_REQUEST_PARAM_ERROR.getMessage() + ":" + detailMessage);
    }


    @ResponseBody
    @ExceptionHandler(value = BindException.class)
    public Result bindExceptionHandler(BindException ex) {
        log.debug("[bindExceptionHandler]", ex);
        // 拼接错误
        StringBuilder detailMessage = new StringBuilder();
        for (ObjectError objectError : ex.getAllErrors()) {
            // 使用 ; 分隔多个错误
            if (detailMessage.length() > 0) {
                detailMessage.append(";");
            }
            // 拼接内容到其中
            detailMessage.append(objectError.getDefaultMessage());
        }
        // 包装 CommonResult 结果
        return Result.fail(Status.INVALID_REQUEST_PARAM_ERROR,
                Status.INVALID_REQUEST_PARAM_ERROR.getMessage() + ":" + detailMessage);
    }
}
